package com.dji.GSDemo.GaodeMap.SDKInterconnection;


import com.dji.GSDemo.GaodeMap.DJIDemoApplication;

import java.util.ArrayList;
import java.util.List;

import dji.sdk.base.BaseProduct;
import dji.sdk.flightcontroller.FlightController;
import dji.sdk.products.Aircraft;

public class SDKConnection {
    FlightController mFlightController;
    List<SDKConnectionListener> listeners = new ArrayList<>();

    private static class Singleton {
        private static final SDKConnection instance = new SDKConnection();
    }

    public static SDKConnection getInstance() {
        return SDKConnection.Singleton.instance;
    }

    private SDKConnection() {
    }

    public void updateProduct(){
        BaseProduct product = DJIDemoApplication.getProductInstance();
        if (product != null && product.isConnected()) {
            if (product instanceof Aircraft) {
                mFlightController = ((Aircraft) product).getFlightController();
            }
        }

        if (mFlightController != null) {
            mFlightController.setOnboardSDKDeviceDataCallback(bytes -> {
                String msg = new String(bytes);
                for(SDKConnectionListener listener : listeners) {
                    listener.onReceive(msg);
                }
            });
        }
    }


    public void addListener(SDKConnectionListener obj) {
        if (listeners == null) {
            throw new NullPointerException();
        } else {
            if (!listeners.contains(obj)) {
                listeners.add(obj);
            }
        }
    }

    public void removeListener(SDKConnectionListener obj) {
        if (listeners == null) {
            throw new NullPointerException();
        } else {
            listeners.remove(obj);
        }
    }

}
